<template>
  <div class="register-page">
    <!-- 头部 -->
    <div class="header d-flex align-items-center">
      <router-link to="/" class="back-button me-3">
        <i class="bi bi-arrow-left"></i>
      </router-link>
      <h5 class="mb-0">注册账号</h5>
    </div>

    <!-- 注册表单 -->
    <div class="form-container">
      <!-- 用户名 -->
      <div class="form-group mb-4">
        <label class="form-label">用户名</label>
        <div class="input-group">
          <input
              type="text"
              class="form-control"
              v-model="form.userName"
              placeholder="请输入用户名"
          >
        </div>
        <div class="form-text text-danger" v-if="errors.userName">
          {{ errors.userName }}
        </div>
      </div>
      <!-- 手机号 -->
      <div class="form-group mb-4">
        <label class="form-label">手机号</label>
        <div class="input-group">
          <input 
            type="tel" 
            class="form-control" 
            v-model="form.phone"
            placeholder="请输入手机号"
          >
        </div>
        <div class="form-text text-danger" v-if="errors.phone">
          {{ errors.phone }}
        </div>
      </div>

      <!-- 验证码 -->
      <div class="form-group mb-4">
        <label class="form-label">验证码</label>
        <div class="input-group">
          <input 
            type="text" 
            class="form-control" 
            v-model="form.code"
            placeholder="请输入验证码"
          >
          <button 
            class="btn btn-outline-primary" 
            type="button"
            :disabled="countdown > 0"
            @click="sendCode"
          >
            {{ countdown > 0 ? `${countdown}s后重新获取` : '获取验证码' }}
          </button>
        </div>
        <div class="form-text text-danger" v-if="errors.code">
          {{ errors.code }}
        </div>
      </div>

      <!-- 密码 -->
      <div class="form-group mb-4">
        <label class="form-label">设置密码</label>
        <div class="input-group">
          <input 
            :type="showPassword ? 'text' : 'password'" 
            class="form-control" 
            v-model="form.password"
            placeholder="请设置登录密码"
          >
          <button 
            class="btn btn-outline-secondary" 
            type="button"
            @click="showPassword = !showPassword"
          >
            <i :class="showPassword ? 'bi bi-eye-slash' : 'bi bi-eye'"></i>
          </button>
        </div>
        <div class="form-text text-danger" v-if="errors.password">
          {{ errors.password }}
        </div>
      </div>

      <!-- 确认密码 -->
      <div class="form-group mb-4">
        <label class="form-label">确认密码</label>
        <div class="input-group">
          <input 
            :type="showConfirmPassword ? 'text' : 'password'" 
            class="form-control" 
            v-model="form.confirmPassword"
            placeholder="请再次输入密码"
          >
          <button 
            class="btn btn-outline-secondary" 
            type="button"
            @click="showConfirmPassword = !showConfirmPassword"
          >
            <i :class="showConfirmPassword ? 'bi bi-eye-slash' : 'bi bi-eye'"></i>
          </button>
        </div>
        <div class="form-text text-danger" v-if="errors.confirmPassword">
          {{ errors.confirmPassword }}
        </div>
      </div>

      <!-- 用户协议 -->
      <div class="form-check mb-4">
        <input 
          class="form-check-input" 
          type="checkbox" 
          id="agreement"
          v-model="form.agreement"
        >
        <label class="form-check-label" for="agreement">
          我已阅读并同意
          <a href="#" class="text-primary" @click.prevent="showAgreement">《用户协议》</a>
          和
          <a href="#" class="text-primary" @click.prevent="showPrivacy">《隐私政策》</a>
        </label>
        <div class="form-text text-danger" v-if="errors.agreement">
          {{ errors.agreement }}
        </div>
      </div>

      <!-- 注册按钮 -->
      <button 
        class="btn btn-primary w-100 mb-3"
        @click="register"
      >注册</button>

      <!-- 登录链接 -->
      <div class="text-center">
        <span class="text-muted">已有账号？</span>
        <router-link to="/login" class="text-primary">立即登录</router-link>
      </div>
    </div>
  </div>
</template>

<script>
import http from "@/router/http";
import router from "@/router/index";
export default {
  name: 'RegisterView',
  data() {
    return {
      form: {
        userName: '',
        phone: '',
        code: '',
        password: '',
        confirmPassword: '',
        agreement: false
      },
      errors: {
        phone: '',
        code: '',
        password: '',
        confirmPassword: '',
        agreement: ''
      },
      showPassword: false,
      showConfirmPassword: false,
      countdown: 0,
      timer: null
    }
  },
  methods: {
    validateUserName() {
      if (!this.form.userName) {
        this.errors.userName = '请输入用户名'
        return false
      }
      this.errors.userName = ''
      return true
    },
    validatePhone() {
      const phoneReg = /^1[3-9]\d{9}$/
      if (!this.form.phone) {
        this.errors.phone = '请输入手机号'
        return false
      }
      if (!phoneReg.test(this.form.phone)) {
        this.errors.phone = '请输入正确的手机号'
        return false
      }
      this.errors.phone = ''
      return true
    },
    validateCode() {
      if (!this.form.code) {
        this.errors.code = '请输入验证码'
        return false
      }
      if (!/^\d{6}$/.test(this.form.code)) {
        this.errors.code = '验证码格式不正确'
        return false
      }
      this.errors.code = ''
      return true
    },
    validatePassword() {
      if (!this.form.password) {
        this.errors.password = '请设置密码'
        return false
      }
      if (this.form.password.length < 6) {
        this.errors.password = '密码长度不能少于6位'
        return false
      }
      this.errors.password = ''
      return true
    },
    validateConfirmPassword() {
      if (!this.form.confirmPassword) {
        this.errors.confirmPassword = '请确认密码'
        return false
      }
      if (this.form.confirmPassword !== this.form.password) {
        this.errors.confirmPassword = '两次输入的密码不一致'
        return false
      }
      this.errors.confirmPassword = ''
      return true
    },
    validateAgreement() {
      if (!this.form.agreement) {
        this.errors.agreement = '请阅读并同意用户协议和隐私政策'
        return false
      }
      this.errors.agreement = ''
      return true
    },
    validate() {
      const validUserName = this.validateUserName()
      const validPhone = this.validatePhone()
      const validCode = this.validateCode()
      const validPassword = this.validatePassword()
      const validConfirmPassword = this.validateConfirmPassword()
      const validAgreement = this.validateAgreement()
      return validUserName && validPhone && validCode && validPassword && validConfirmPassword && validAgreement
    },
    startCountdown() {
      this.countdown = 60
      this.timer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--
        } else {
          clearInterval(this.timer)
        }
      }, 1000)
    },
    async sendCode() {
      if (!this.validatePhone()) return
      if (this.countdown > 0) return

      try {
        const requestData = {
          phone: this.form.phone,
          sendType: 1
        }
        const response = await http.post('/student/user/sendSmsCode', requestData);
        console.log('发送验证码到:', this.form.phone)
        this.startCountdown()
      } catch (error) {
        console.error('发送验证码失败:', error)
      }
    },
    async register() {
      if (!this.validate()) return

      try {
        const requestData = {
          userName: this.form.userName,
          password: this.form.password,
          validCode: this.form.code,
          phone: this.form.phone,
          sendType: 1
        }
        const response = await http.post('/student/user/register', requestData);
        if (response.data.code === 1) {
          console.log('注册成功:', response.data)
          alert("注册成功")
          // router.push('/basic-info?userId=' + response.data.response);
          router.push({
            name: 'BasicInfoView',
            query: {
              userId: response.data.response,
              userName: this.form.userName,
              password: this.form.password
            }
          });
        } else if(response.data.code === 2) {
          alert(response.data.message)
          console.error('注册失败:', response.data.message)
        }else {
          alert(response.data.message)
          console.error('注册失败:', response.data.message)
        }

      } catch (error) {
        console.error('注册失败:', error)
      }
    },
    showAgreement() {
      router.push("/useragreement")
    },
    showPrivacy() {
      router.push("/privacypolicy")
    }
  },
  beforeUnmount() {
    if (this.timer) {
      clearInterval(this.timer)
    }
  }
}
</script>

<style scoped>
.register-page {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  background: linear-gradient(135deg, #00b8a9, #00a19a);
  color: white;
  padding: 15px;
  position: relative;
}

.back-button {
  color: white;
  text-decoration: none;
  font-size: 1.2rem;
}

.form-container {
  padding: 20px;
}

.form-label {
  font-size: 0.9rem;
  color: #666;
  margin-bottom: 8px;
}

.form-text {
  font-size: 0.8rem;
  margin-top: 4px;
}

.form-check-label {
  font-size: 0.9rem;
  color: #666;
}
</style> 